import { EventManager } from "../eventManager/EventManager";
import { EventType } from "../eventManager/EventType";

export class WebSocketConnector {
    private _socket: WebSocket;
    private _messageQueue: any[] = [];
    private _isConnected = false;
    private _url: string;
    private _eventManager: EventManager = EventManager.getInstance();

    connect(url: string): void {
        this._url = url;
        this._socket = new WebSocket(url);
        this._socket.binaryType = 'arraybuffer';

        this._socket.onopen = () => {
            this._isConnected = true;
            this.flushMessageQueue();

            this._eventManager.emit(EventType.NET_OPEN);
            // this.emit('open');
        };

        this._socket.onclose = (event) => {
            this._isConnected = false;
            this._eventManager.emit(EventType.NET_CLOSE, event);
            // this.emit('close', event);
        };

        this._socket.onmessage = (event) => {
            this._eventManager.emit(EventType.NET_MESSAGE, event.data);
            // this.emit('message', event.data);
        };

        this._socket.onerror = (error) => {
            this._eventManager.emit(EventType.NET_ERROR, error);
            // this.emit('error', error);
        };
    }

    reconnect(): void {
        if (this._url) {
            this.connect(this._url);
        }
    }

    send(data: ArrayBuffer): void {
        if (this._isConnected) {
            this._socket.send(data);
        } else {
            this._messageQueue.push(data);
        }
    }

    private flushMessageQueue(): void {
        while (this._messageQueue.length > 0) {
            const data = this._messageQueue.shift();
            this._socket.send(data);
        }
    }

    close(): void {
        if (this._socket) {
            this._socket.close();
        }
    }
}
